using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Acms.AcmsControls.ContentControls.FrontEnd;

public partial class Templates_Mp3Competition : BaseTemplate
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HyperLink lnkLogin = viewEnter.FindControl("lnkLogin") as HyperLink;
            if (lnkLogin != null)
            {
                lnkLogin.DataBind();
            }
            //flashHeader.Variables.Add("SiteRoot", AcmsContext.SiteRoot);
            SetFlashHeaderVariables(flashHeader);

            HyperLink btnEntryCreate = viewEnter.FindControl("btnEntryCreate") as HyperLink;
            if (btnEntryCreate != null)
            {
                btnEntryCreate.DataBind();
            }

            Acms.Bll.PostControl allowEntries = AcmsContext.CurrentPost.FindPostControl("AllowEntries");
            if (allowEntries != null)
            {
                Acms.AcmsControls.TextContentControlProperties prop = allowEntries.GetProperties<Acms.AcmsControls.TextContentControlProperties>();
                if (prop != null && prop.Text != null && prop.Text.ToLower() == "false")
                {
                    viewEnter.Visible = false;
                }
                else
                {
                    viewEnter.Visible = true;
                }
                ShowUserEntryButtons();
            }

            Acms.Bll.PostControl tmpAllowVotes = AcmsContext.CurrentPost.FindPostControl("AllowVotes");
            if (tmpAllowVotes != null)
            {
                Acms.AcmsControls.TextContentControlProperties prop = tmpAllowVotes.GetProperties<Acms.AcmsControls.TextContentControlProperties>();
                if (prop != null && prop.Text != null && prop.Text.ToLower() == "false")
                {
                    allowVotes = false;
                }
                else
                {
                    allowVotes = true;
                }
            }
        }
    }

    private void HideUserEntryButtons()
    {
        if (Request.IsAuthenticated)
        {
            Panel pnlUsersEntryButtons = viewEnter.FindControl("pnlUsersEntryButtons") as Panel;
            pnlUsersEntryButtons.Visible = false;
        }
    }

    private void ShowUserEntryButtons()
    {
        if (Request.IsAuthenticated)
        {
            Panel pnlUsersEntryButtons = viewEnter.FindControl("pnlUsersEntryButtons") as Panel;
            pnlUsersEntryButtons.Visible = true;

            HyperLink btnEntryCreate = viewEnter.FindControl("btnEntryCreate") as HyperLink;
            LinkButton btnEntryView = viewEnter.FindControl("btnEntryView") as LinkButton;
            LinkButton btnEntryEdit = viewEnter.FindControl("btnEntryEdit") as LinkButton;
            LinkButton btnEntryDelete = viewEnter.FindControl("btnEntryDelete") as LinkButton;

            btnEntryCreate.Visible = GetEntry() == null;
            btnEntryView.Visible = !btnEntryCreate.Visible;
            btnEntryEdit.Visible = !btnEntryCreate.Visible;
            btnEntryDelete.Visible = !btnEntryCreate.Visible;
        }
    }

    private Acms.Bll.UserPostUpload entry = null;
    private Acms.Bll.UserPostUpload GetEntry()
    {
        if (entry == null && Request.IsAuthenticated)
        {
            List<Acms.Bll.UserPostUpload> uploads = Acms.Bll.UserPostUpload.GetAllByUserIdAndPostId(User.Identity.User.Id, AcmsContext.PostId);
            if (uploads != null && uploads.Count > 0)
            {
                entry = uploads[0];
            }
        }
        return entry;
   }

    protected void dsUserUpload_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.UserPostUpload> e)
    {
        e.SetData(GetEntry());
    }

    protected void dvEntry_DataBound(object sender, EventArgs e)
    {
        DetailsView dv = sender as DetailsView;
    }

    protected void btnEntryCreate_Click(object sender, EventArgs e)
    {
        DetailsView dvEntry = viewEnter.FindControl("dvEntry") as DetailsView;
        dvEntry.ChangeMode(DetailsViewMode.Insert);
        Panel pnlEnter = viewEnter.FindControl("pnlEnter") as Panel;
        pnlEnter.Visible = true;
        HideUserEntryButtons();
    }

    protected void btnEntryView_Click(object sender, EventArgs e)
    {
        Acms.Bll.UserPostUpload userEntry = GetEntry();
        if (userEntry != null)
        {
            Selected = userEntry;
            pnlSelected.DataBind();
            updateSelected.Update();
        }
    }

    protected void btnEntryEdit_Click(object sender, EventArgs e)
    {
        DetailsView dvEntry = viewEnter.FindControl("dvEntry") as DetailsView;
        dvEntry.ChangeMode(DetailsViewMode.Edit);
        Panel pnlEnter = viewEnter.FindControl("pnlEnter") as Panel;
        pnlEnter.Visible = true;
        HideUserEntryButtons();
        Selected = null;
        pnlSelected.DataBind();
    }

    protected void btnEntryDelete_Click(object sender, EventArgs e)
    {
        Acms.Bll.UserPostUpload tmp = GetEntry();
        if (tmp != null)
        {
            if (selectedId == tmp.Id)
            {
                Selected = null;
                pnlSelected.DataBind();
                updateSelected.Update();
            }
            tmp.Delete();
            //resert local store
            entry = null;
        }
        Panel pnlEnter = viewEnter.FindControl("pnlEnter") as Panel;
        pnlEnter.Visible = false;
        ShowUserEntryButtons();
        dlEntrants.DataBind();
    }

    protected void dvEntry_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        //check size
        e.Cancel = CheckFileSizes(sender as DetailsView);
    }

    protected void dvEntry_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        //check size
        e.Cancel = CheckFileSizes(sender as DetailsView);
    }

    protected bool CheckFileSizes(DetailsView view)
    {
        bool cancel = false;
        if (view != null)
        {
            Panel pnlFileError = viewEnter.FindControl("pnlFileError") as Panel;
            FileUpload image = view.FindControl("image") as FileUpload;
            if (image != null && image.HasFile && image.PostedFile.ContentLength > 3000000)
            {
                cancel = true;
                pnlFileError.Visible = true;
            }
            FileUpload song = view.FindControl("song") as FileUpload;
            if (song != null && song.HasFile && song.PostedFile.ContentLength > 6000000)
            {
                cancel = true;
                pnlFileError.Visible = true;
            }
        }
        return cancel;
    }

    protected void dvEntry_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
    {
        if (e.Exception == null)
        {
            Panel pnlEnter = viewEnter.FindControl("pnlEnter") as Panel;
            pnlEnter.Visible = false;
            ShowUserEntryButtons();
            dlEntrants.DataBind();

        }
        else
        {
            e.ExceptionHandled = ProcessException(sender as DetailsView, e.Exception);
        }
    }

    protected void dvEntry_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        if (e.Exception == null)
        {
            Acms.Bll.Email email = Acms.Bll.Email.CreateInstance(User.Identity.User, MapPath("~/Emails/Mp3Competition.xml"));
            email.Format("EntryDate", DateTime.Now.ToLongDateString());
            email.Format("CompetitionName", AcmsContext.CurrentPost.DisplayName);
            email.Send();

            Panel pnlEnter = viewEnter.FindControl("pnlEnter") as Panel;
            pnlEnter.Visible = false;
            ShowUserEntryButtons();
            dlEntrants.DataBind();
        }
        else
        {
            e.ExceptionHandled = ProcessException(sender as DetailsView, e.Exception);
        }
    }

    private bool ProcessException(DetailsView view, Exception exception)
    {
        if (view != null)
        {
            Panel pnlFileError = viewEnter.FindControl("pnlFileError") as Panel;
            if (exception is Acms.Exceptions.InvalidFileTypeException)
            {
                pnlFileError.Visible = true;
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }



    protected void dvEntry_ItemCommand(object sender, DetailsViewCommandEventArgs e)
    {
        if (e.CommandName == "Cancel")
        {
            Panel pnlEnter = viewEnter.FindControl("pnlEnter") as Panel;
            pnlEnter.Visible = false;
            ShowUserEntryButtons();
        }
    }

    protected void dsUserUpload_BeforeUpdating(object sender, Acms.DataControls.BeforeUpdatingEventArgs e)
    {
        if (e.Action == Acms.DataControls.UpdateAction.Insert)
        {
            e.Values.Add("UserId", User.Identity.User.Id);
            e.Values.Add("PostId", AcmsContext.PostId);
            e.Values.Add("IPAddress", Request.ServerVariables["REMOTE_ADDR"]);
        }
    }

    protected void dsUserUpload_UpdatingData(object sender, Acms.DataControls.UpdatingDataEventArgs<Acms.Bll.UserPostUpload> e)
    {
        DetailsView dvEntry = viewEnter.FindControl("dvEntry") as DetailsView;
        if (dvEntry != null)
        {
            FileUpload song = dvEntry.FindControl("song") as FileUpload;
            if (song != null && song.HasFile)
            {
                e.Item.SetFile("Track", Acms.Bll.File.FileTypes.Mp3, song.PostedFile, song.FileBytes);
            }

            TextBox songTitle = dvEntry.FindControl("songTitle") as TextBox;
            if (songTitle != null)
            {
                e.Item.SetTextValue("TrackTitle", songTitle.Text);
            }

        }
    }

    protected void dsUserUpload_UpdateData(object sender, Acms.DataControls.UpdateDataEventArgs<Acms.Bll.UserPostUpload> e)
    {
        DetailsView dvEntry = viewEnter.FindControl("dvEntry") as DetailsView;
        if (dvEntry != null)
        {
            if (e.HasChanged())
            {
                e.Item.MarkAsUnReviewed();
            }
            FileUpload image = dvEntry.FindControl("image") as FileUpload;
            if (image != null && image.HasFile)
            {
                e.Item.Update(Acms.Bll.File.FileTypes.Image, image.PostedFile, image.FileBytes);
            }
            else
            {
                e.Item.Update();
            }
            e.Changes = 1;
        }

    }

    protected void flashTrack_DataBinding(object sender, EventArgs e)
    {
        Acms.WebControls.FlashControl flashTrack = sender as Acms.WebControls.FlashControl;
        DetailsView dv = (DetailsView)flashTrack.NamingContainer;
        Acms.Bll.UserPostUpload upload = dv.DataItem as Acms.Bll.UserPostUpload;
        Acms.Bll.UserPostUploadFile file = upload.GetFile("Track");
        flashTrack.Variables.Add("trackName", Page.ResolveUrl(string.Concat("~/File.aspx?Id=", file.FileId)));
    }

    protected void dlEntrants_ItemCommand(object sender, Acms.WebControls.AcmsDataListItemCommandEventArgs e)
    {
        if (e.CommandName == "Show")
        {
            try
            {
                selectedId = int.Parse(e.CommandArgument as string);
            }
            catch (FormatException)
            {
            }
            pnlSelected.DataBind();
            updateSelected.Update();
        }
    }

    protected void dlEntrants_ItemDataBound(object sender, Acms.WebControls.AcmsDataListItemEventArgs e)
    {
        if (e.Item.IsSeperator)
        {
            if (e.Item.ItemIndex > 0 && (e.Item.ItemIndex + 1) % 3 == 0)
                e.Item.Visible = true;
            else
                e.Item.Visible = false;
        }
        else if (e.Item.IsDataItem)
        {
            Image imgSuspended = e.Item.FindControl("imgSuspended") as Image;
            ImageButton imgReported = e.Item.FindControl("imgReported") as ImageButton;
            AcmsImageLinkButton imgThumb = e.Item.FindControl("imgThumb") as AcmsImageLinkButton;
            Acms.Bll.UserPostUpload image = e.Item.DataItem as Acms.Bll.UserPostUpload;
            if (image != null && imgSuspended != null && imgReported != null && imgThumb != null)
            {
                imgSuspended.Visible = false;
                imgReported.Visible = false;
                imgThumb.Visible = false;
                if (image.Suspended)
                {
                    imgSuspended.Visible = true;
                }
                else if (image.Reported)
                {
                    imgReported.Visible = true;
                }
                else
                {
                    imgThumb.Visible = true;
                }

            }
        }
    }

    protected void dsEntrants_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.UserPostUpload> e)
    {
        e.SetData(Acms.Bll.UserPostUpload.GetAllByPostId(AcmsContext.PostId));
    }

    private int selectedId = 0;
    private Acms.Bll.UserPostUpload selected;
    protected Acms.Bll.UserPostUpload Selected
    {
        get 
        {
            if (selected == null && selectedId > 0)
            {
                selected = Acms.Bll.UserPostUpload.GetById(selectedId);
            }
            return selected;
        }
        set
        {
            if (value != null)
            {
                selectedId = value.Id;
                selected = value;
            }
            else
            {
                selectedId = 0;
                selected = null;
            }
        }
    }

    private bool allowVotes = true;

    public bool AllowVotes
    {
        get { return allowVotes; }
    }
	

    protected override object SaveViewState()
    {
        ViewState["SelectedId"] = selectedId;
        ViewState["AllowVotes"] = allowVotes;
        return base.SaveViewState();
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        if (ViewState["SelectedId"] is int)
            selectedId = (int)ViewState["SelectedId"];
        if (ViewState["AllowVotes"] is bool)
            allowVotes = (bool)ViewState["AllowVotes"];
    }

    protected void pnlSelected_DataBinding(object sender, EventArgs e)
    {
        if (Selected != null && !Selected.Suspended)
        {
            pnlSelected.Visible = true;
            pnlSuspended.Visible = false;

            selectedTrack.Variables["trackName"] = Page.ResolveUrl(string.Concat("~/File.aspx?Id=", Selected.GetFile("Track").FileId));
            imgBand.FileId = Selected.FileId;
            lblTrackName.Text = Selected.GetTextValue("TrackTitle");
            lblBandName.Text = Selected.Title;
            lblBio.Text = Selected.Comment;


            //see if user has voted
            if(!Request.IsAuthenticated)
            {
                lblVote.Visible = false;
                btnVote.Visible = false;
            }
            else
            {
                lblVote.Visible = false;
                btnVote.Visible = AllowVotes;
                List<Acms.Bll.UserPostUploadVote> votes = Acms.Bll.UserPostUploadVote.GetAllByUserIdAndPostId(User.Identity.User.Id, AcmsContext.PostId);
                if (votes != null)
                {
                    foreach (Acms.Bll.UserPostUploadVote vote in votes)
                    {
                        if (vote.Score == 1)
                        {
                            lblVote.Visible = true;
                            lblVote.Text = string.Format("You have currently voted for '{0}'", vote.Title);
                            break;
                        }
                    }
                }
            }

            if (AllowVotes)
            {
                lblTotalVotes.Text = "(0 Votes)";
                List<Acms.Bll.UserPostUploadVoteTotal> totals = Acms.Bll.UserPostUploadVoteTotal.GetAllByUploadId(Selected.Id);
                foreach (Acms.Bll.UserPostUploadVoteTotal total in totals)
                {
                    if (total.Score == 1)
                    {
                        lblTotalVotes.Text = string.Format("({0} Votes)", total.Total);
                    }
                }
            }

            if (Selected.Reported)
            {
                btnReport.Visible = false;
                lblReported.Visible = true;
            }
            else
            {
                lblReported.Visible = false;
                btnReport.Visible = !Selected.Reviewed;
                if (Request.IsAuthenticated)
                {
                    if (Selected.UserId == User.Identity.User.Id)
                    {
                        btnReport.Visible = false;
                    }
                }
            }
        }
        else if (Selected != null && Selected.Suspended)
        {
            pnlSelected.Visible = false;
            pnlSuspended.Visible = true;
        }
        else
        {
            pnlSelected.Visible = false;
            pnlSuspended.Visible = false;
        }
    }

    protected void btnVote_Click(object sender, EventArgs e)
    {
        List<Acms.Bll.UserPostUploadVote> votes = Acms.Bll.UserPostUploadVote.GetAllByUserIdAndPostId(User.Identity.User.Id, AcmsContext.PostId);
        Acms.Bll.UserPostUploadVote newVote = Acms.Bll.UserPostUploadVote.CreateInstance(User.Identity.User.Id, selectedId);
        if(votes != null)
        {
            foreach(Acms.Bll.UserPostUploadVote tmp in votes)
            {
                if(tmp.UserPostUploadId == selectedId)
                {
                    newVote = tmp;
                }
                else if(tmp.Score == 1)
                {
                    tmp.Score = 0;
                    tmp.Update();
                }
            }
        }

        if(newVote.Score != 1)
        {
            newVote.Score = 1;
            newVote.Update();
        }


        pnlSelected.DataBind();
    }


    protected void btnReport_Click(object sender, EventArgs e)
    {
        if (Selected != null)
        {
            Selected.Report();
            Selected.Update();
            pnlSelected.DataBind();
            dlEntrants.DataBind();
            updEntrants.Update();
        }
    }



}
